package com.aizuda.security.example;

import com.aizuda.common.toolkit.JacksonUtils;
import com.baomidou.kisso.common.encrypt.MD5;
import com.baomidou.kisso.common.encrypt.RSA;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.SortedMap;
import java.util.TreeMap;

public class SignTest {

    public static void main(String[] args) throws Exception {
        SortedMap<String, String> parameterMap = new TreeMap<>();
        parameterMap.put("username", "test");
        parameterMap.put("password", "123");
        String timestamp = String.valueOf(System.currentTimeMillis());
        String jsonStr = JacksonUtils.toJSONString(parameterMap);
        String jsonMd5 = MD5.toMD5(jsonStr);

        // md5(md5(内容) + 时间戳) = sign
        String sign = MD5.toMD5(jsonMd5 + timestamp);
        System.err.println("ts=" + timestamp + "&sn=" + sign);

        // RSA + base64 加密签名
        String rsaBase64 = Base64.encodeBase64String(RSA.encryptByPublicKey(jsonStr.getBytes(StandardCharsets.UTF_8),
                "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCMlG0T0/SvQdDW1Uvm3CQITdo/x/sr+ADdnEFQWjTuJFgAuMIvk1OqUQDr0D58brQWbkdjji1pqsxNf7U3e+6Ni1Gc10FauIKQBcwRRGn/V3Aj+167htF0Ytx9zARg/5C693FHmtc76cfsB4J03Wrigiz+Sr1vOSbbQ5NoSLKxfQIDAQAB"));
        System.err.println("密文：\n" + rsaBase64);
        String signRsa = DigestUtils.md5DigestAsHex((MD5.toMD5(rsaBase64) + timestamp).getBytes(StandardCharsets.UTF_8));
        System.err.println("ts=" + timestamp + "&sn=" + signRsa);
    }
}
